import { ref, reactive, computed, onMounted } from 'vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import { Search, Edit, Delete, View } from '@element-plus/icons-vue'
import { getUserAuditList, getUserAuditDetail, auditUser } from '@/api/admin'

// 查询条件
const queryParams = reactive({
  userId: '',
  auditType: '',
  status: '',
  page: 1,
  size: 10
})

// 表格数据
const tableData = ref([])
const loading = ref(false)
const total = ref(0)

// 详情对话框
const detailDialog = reactive({
  visible: false,
  loading: false,
  data: null
})

// 获取审核列表数据
const getAuditList = async () => {
  loading.value = true
  try {
    const response = await getUserAuditList(queryParams)
    if (response.code === 200) {
      tableData.value = response.data.records || []
      total.value = response.data.total || 0
    } else {
      ElMessage.error(response.message || '获取审核列表失败')
    }
  } catch (error) {
    console.error('获取审核列表失败:', error)
    ElMessage.error('获取审核列表失败，请稍后重试')
  } finally {
    loading.value = false
  }
}

// 初始化加载
onMounted(() => {
  getAuditList()
})

// 处理查询
const handleQuery = () => {
  queryParams.page = 1
  getAuditList()
}

// 处理重置
const handleReset = () => {
  Object.keys(queryParams).forEach(key => {
    if (key !== 'page' && key !== 'size') {
      queryParams[key] = ''
    }
  })
  queryParams.page = 1
  getAuditList()
}

// 处理页码变化
const handlePageChange = (page) => {
  queryParams.page = page
  getAuditList()
}

// 处理每页条数变化
const handleSizeChange = (size) => {
  queryParams.size = size
  queryParams.page = 1
  getAuditList()
}

// 处理查看详情
const handleViewDetail = async (row) => {
  detailDialog.visible = true
  detailDialog.loading = true
  detailDialog.data = { ...row }
  
  try {
    const response = await getUserAuditDetail(row.id)
    if (response.code === 200) {
      detailDialog.data = response.data
    } else {
      ElMessage.error(response.message || '获取审核详情失败')
    }
  } catch (error) {
    console.error('获取审核详情失败:', error)
    ElMessage.error('获取审核详情失败，请稍后重试')
  } finally {
    detailDialog.loading = false
  }
}

// 处理审核
const handleAudit = (row, status) => {
  const action = status === 1 ? '通过' : '拒绝'
  
  ElMessageBox.prompt(
    `确定要${action}此审核吗？`,
    '审核意见',
    {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      type: status === 1 ? 'info' : 'warning',
      inputPlaceholder: '请输入审核意见(可选)'
    }
  ).then(({ value: remark }) => {
    processAudit(row.id, status, remark)
  }).catch(() => {
    // 取消操作，无需处理
  })
}

// 处理审核提交
const processAudit = async (id, status, remark) => {
  try {
    // 获取当前登录用户ID，这里假设从localStorage获取
    const currentUser = JSON.parse(localStorage.getItem('user') || '{}')
    const auditorId = currentUser.id || 1 // 如果没有则默认使用ID为1的管理员
    
    const response = await auditUser(id, { status, remark, auditorId })
    
    if (response.code === 200) {
      ElMessage.success(`审核已${status === 1 ? '通过' : '拒绝'}`)
      
      // 更新表格中的数据
      const index = tableData.value.findIndex(item => item.id === id)
      if (index !== -1) {
        tableData.value[index].status = status
        tableData.value[index].remark = remark
        tableData.value[index].auditorId = auditorId
        tableData.value[index].auditTime = new Date()
      }
      
      // 如果详情对话框打开，也更新详情数据
      if (detailDialog.visible && detailDialog.data && detailDialog.data.id === id) {
        detailDialog.data.status = status
        detailDialog.data.remark = remark
        detailDialog.data.auditorId = auditorId
        detailDialog.data.auditTime = new Date()
      }
    } else {
      ElMessage.error(response.message || '审核处理失败')
    }
  } catch (error) {
    console.error('审核处理失败:', error)
    ElMessage.error('审核处理失败，请稍后重试')
  }
}

// 格式化审核类型
const formatAuditType = (type) => {
  switch (type) {
    case 1: return '用户注册'
    case 2: return '车辆审核'
    case 3: return '其他'
    default: return '未知'
  }
}

// 格式化审核状态
const formatStatus = (status) => {
  switch (status) {
    case 0: return '待审核'
    case 1: return '已通过'
    case 2: return '已拒绝'
    default: return '未知'
  }
}

// 格式化日期时间
const formatDateTime = (dateTimeStr) => {
  if (!dateTimeStr) return '-'
  const date = new Date(dateTimeStr)
  return date.toLocaleString('zh-CN', {
    year: 'numeric',
    month: '2-digit',
    day: '2-digit',
    hour: '2-digit',
    minute: '2-digit',
    second: '2-digit'
  }).replace(/\//g, '-')
}

<template>
  <div class="user-audit-container">
    <el-card class="filter-container">
      <el-form :inline="true" :model="queryParams">
        <el-form-item label="用户ID">
          <el-input v-model="queryParams.userId" placeholder="请输入用户ID" clearable />
        </el-form-item>
        <el-form-item label="审核类型">
          <el-select v-model="queryParams.auditType" placeholder="请选择审核类型" clearable>
            <el-option label="用户注册" value="1" />
            <el-option label="车辆审核" value="2" />
            <el-option label="其他" value="3" />
          </el-select>
        </el-form-item>
        <el-form-item label="审核状态">
          <el-select v-model="queryParams.status" placeholder="请选择审核状态" clearable>
            <el-option label="待审核" value="0" />
            <el-option label="已通过" value="1" />
            <el-option label="已拒绝" value="2" />
          </el-select>
        </el-form-item>
        <el-form-item>
          <el-button type="primary" :icon="Search" @click="handleQuery">查询</el-button>
          <el-button @click="handleReset">重置</el-button>
        </el-form-item>
      </el-form>
    </el-card>

    <el-card class="table-container">
      <el-table v-loading="loading" :data="tableData" style="width: 100%" border>
        <el-table-column prop="id" label="ID" width="80" />
        <el-table-column prop="userId" label="用户ID" width="100" />
        <el-table-column label="审核类型" width="120">
          <template #default="scope">
            {{ formatAuditType(scope.row.auditType) }}
          </template>
        </el-table-column>
        <el-table-column prop="relatedInfo" label="关联信息" min-width="150" show-overflow-tooltip />
        <el-table-column label="审核状态" width="120">
          <template #default="scope">
            <el-tag :type="scope.row.status === 0 ? 'info' : scope.row.status === 1 ? 'success' : 'danger'">
              {{ formatStatus(scope.row.status) }}
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column prop="createdAt" label="创建时间" width="170" show-overflow-tooltip>
          <template #default="scope">
            {{ formatDateTime(scope.row.createdAt) }}
          </template>
        </el-table-column>
        <el-table-column label="操作" width="220" fixed="right">
          <template #default="scope">
            <el-button type="primary" :icon="View" size="small" @click="handleViewDetail(scope.row)">
              查看
            </el-button>
            <el-button v-if="scope.row.status === 0" type="success" size="small" @click="handleAudit(scope.row, 1)">
              通过
            </el-button>
            <el-button v-if="scope.row.status === 0" type="danger" size="small" @click="handleAudit(scope.row, 2)">
              拒绝
            </el-button>
          </template>
        </el-table-column>
      </el-table>

      <div class="pagination-container">
        <el-pagination
          v-model:current-page="queryParams.page"
          v-model:page-size="queryParams.size"
          :page-sizes="[10, 20, 50, 100]"
          layout="total, sizes, prev, pager, next, jumper"
          :total="total"
          @size-change="handleSizeChange"
          @current-change="handlePageChange"
        />
      </div>
    </el-card>

    <!-- 详情对话框 -->
    <el-dialog v-model="detailDialog.visible" title="审核详情" width="600px" append-to-body>
      <div v-loading="detailDialog.loading" class="detail-container">
        <el-descriptions :column="1" border>
          <el-descriptions-item label="审核ID">{{ detailDialog.data?.id }}</el-descriptions-item>
          <el-descriptions-item label="用户ID">{{ detailDialog.data?.userId }}</el-descriptions-item>
          <el-descriptions-item label="审核类型">{{ formatAuditType(detailDialog.data?.auditType) }}</el-descriptions-item>
          <el-descriptions-item label="关联ID">{{ detailDialog.data?.relatedId }}</el-descriptions-item>
          <el-descriptions-item label="关联信息">{{ detailDialog.data?.relatedInfo }}</el-descriptions-item>
          <el-descriptions-item label="审核状态">
            <el-tag :type="detailDialog.data?.status === 0 ? 'info' : detailDialog.data?.status === 1 ? 'success' : 'danger'">
              {{ formatStatus(detailDialog.data?.status) }}
            </el-tag>
          </el-descriptions-item>
          <el-descriptions-item label="审核意见">{{ detailDialog.data?.remark || '无' }}</el-descriptions-item>
          <el-descriptions-item label="审核人ID">{{ detailDialog.data?.auditorId || '无' }}</el-descriptions-item>
          <el-descriptions-item label="审核时间">{{ detailDialog.data?.auditTime ? formatDateTime(detailDialog.data.auditTime) : '未审核' }}</el-descriptions-item>
          <el-descriptions-item label="创建时间">{{ formatDateTime(detailDialog.data?.createdAt) }}</el-descriptions-item>
          <el-descriptions-item label="更新时间">{{ formatDateTime(detailDialog.data?.updatedAt) }}</el-descriptions-item>
        </el-descriptions>
      </div>
      <template #footer>
        <div class="dialog-footer">
          <el-button @click="detailDialog.visible = false">关闭</el-button>
          <el-button v-if="detailDialog.data?.status === 0" type="success" @click="handleAudit(detailDialog.data, 1)">
            通过
          </el-button>
          <el-button v-if="detailDialog.data?.status === 0" type="danger" @click="handleAudit(detailDialog.data, 2)">
            拒绝
          </el-button>
        </div>
      </template>
    </el-dialog>
  </div>
</template>

<style scoped>
.user-audit-container {
  padding: 20px;
}

.filter-container {
  margin-bottom: 20px;
}

.table-container {
  margin-bottom: 20px;
}

.pagination-container {
  margin-top: 20px;
  display: flex;
  justify-content: flex-end;
}

.detail-container {
  max-height: 60vh;
  overflow-y: auto;
}

.dialog-footer {
  display: flex;
  justify-content: flex-end;
}
</style> 